from . import admin_blue
from flask import render_template, request, session, redirect, url_for, g, abort, jsonify, sessions
from info.models import User, News, Category
import logging, time, datetime
from info.utils.comment import user_login_data
from info import constants, response_code,db

@admin_blue.route('/login', methods=['GET', 'POST'])
@user_login_data
def admin_login():
    """
    管理员登录界面
    1 展示登录界面逻辑
    2 实现管理后台逻辑
    :return:
    """
    # 1　展示登录界面逻辑
    if request.method == 'GET':
        # 增加的优化逻辑，如果当前的管理已是登录状态，那么在进入admin/login时，直接进入主页
        user = g.user
        if user and user.is_admin:
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/login.html')

    # 2　实现后台登录逻辑
    if request.method == 'POST':
        """
        1 接受参数
        2 校验参数
        3 查询登录用户和校验密码，用户必须是管理员　user.is_admin == True
        4 状态保持　设置session
        5 响应登录结果
        """

        # 接受参数
        username = request.form.get('username')
        password = request.form.get('password')

        # 校验参数
        if not all([username, password]):
            return render_template('admin/login.html', errmsg='缺少参数')

        # 查询登录用户和校验密码，用户必须是管理严
        try:
            user = User.query.filter(User.nick_name == username, User.is_admin ==True).first()
        except Exception as e:
            logging.error(e)
            return render_template('admin/login.html', errmsg='查询用户失败')
        if not user:
            return render_template('admin/login.html', errmsg='用户不存在')

        if not user.check_password(password):
            return render_template('admin/login.html', errmsg='密码错误')

        # 状态保持　设置session

        session['nick_name'] = user.nick_name
        session['user_id'] = user.id
        session['is_admin'] = True
        session['mobile'] = user.mobile

        # 返回响应结果
        return redirect(url_for('admin.admin_index'))


@admin_blue.route('/')
@user_login_data
def admin_index():
    """站点主页显示
    """
    # 优化进入主页逻辑,如果管理员进入主页,必须为登录状态反之，引导到登录界面
    user = g.user
    if not user:
        return redirect(url_for('admin.admin_login'))
    # 构造渲染数据
    context = {
        'user': user.to_dict() if user else None
    }

    return render_template('admin/index.html', context=context)


@admin_blue.route('/user_count')
def user_count():
    """
    用户统计
    1　查询用户总人数
    2　查询用户月增数
    3　查询用户日增数
    4　查询用户登录活跃数
    5　渲染统计界面
    :return:
    """
    # 1 查询用户总数量
    total_count = 0
    month_count = 0
    day_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        logging.error(e)

    # 2 查询用户月增数
    t = time.localtime()
    # 拼接当前月开始时间 ： 2018-08-01 00：00：00
    month_begin_str = '%d-%02d-01' % (t.tm_year, t.tm_mon)
    # 再将时间字符串转成时间对象，因为数据库中的create_time是时间对象，方便比较计算
    month_begin_date = datetime.datetime.strptime(month_begin_str, '%Y-%m-%d')

    # 根据month_begin_date查询月新增数：只要create_time>=当前月开始时间的都是当前月新增用户
    try:
        month_count = User.query.filter(User.is_admin==False, User.create_time>=month_begin_date).count()
    except Exception as e:
        logging.error(e)

    # 3　查询用户日增数
    day_begin_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    day_begin_date = datetime.datetime.strptime(day_begin_str, '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin==False, User.create_time>=day_begin_date).count()
    except Exception as e:
        logging.error(e)

    # 4.查询用户日活跃量:每一天有多少个用户登录了，依据last_login作为判断的依据
    # 查询今天开始的时间 08月20日 00:00:00
    today_begin = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
    today_begin_date = datetime.datetime.strptime(today_begin, '%Y-%m-%d')

    active_date = []
    active_count = []
    # 计算今天往过去推15天
    for i in range(15):
        # 计算一天开始
        begin_date = today_begin_date - datetime.timedelta(days=i)
        # 计算一天结束
        end_date = today_begin_date - datetime.timedelta(days=(i - 1))

        # 查询每一天的日活跃量
        count = User.query.filter(User.is_admin==False, User.last_login>=begin_date, User.last_login<end_date).count()

        active_count.append(count)
        # 需要将datetime类型的begin_date，转成时间字符串，因为前段的折线图框架需要的是字符串
        active_date.append(datetime.datetime.strftime(begin_date, '%Y-%m-%d'))

    # 为了保证今天在X轴的最左侧，需要反转列表
    active_date.reverse()
    active_count.reverse()




    context = {
        'total_count': total_count,
        'month_count': month_count,
        'day_count': day_count,
        'active_date': active_date,
        'active_count': active_count
    }


    return render_template('admin/user_count.html', context=context)


@admin_blue.route('/user_list')
def user_list():
    """用户列表"""

    # 1　接受参数
    page = request.args.get('p', 1)

    # 2　校验参数
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1

    # 3 分页查询
    users = []
    total_page = 1
    current_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        users = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        logging.error(e)


    # 构造渲染数据
    user_dict_list = []
    for user in users:
        user_dict_list.append(user.to_admin_dict())

    context = {
        'users': user_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }

    # 返回响应结果
    return render_template('admin/user_list.html', context=context)


@admin_blue.route('/news_review')
def news_review():
    """新闻审核"""

    # 接受参数
    page = request.args.get('p', 1)
    keyword = request.args.get('keyword')

    # 校验参数
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1

    # 分页查询
    news_list = []
    total_page = 1
    current_page = 1
    try:
        if keyword:
            paginate = News.query.filter(News.status != 0, News.title.contains(keyword)).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:
            paginate = News.query.filter(News.status != 0).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        logging.error(e)


    # 构造渲染数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {
        'news_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }

    # 响应结果
    return render_template('admin/news_review.html', context=context)


@admin_blue.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    """
    新闻审核详情页
    :return:
    """
    # 查询需要审核的新闻的详情页信息
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        abort(404)
    if not news:
        abort(404)

    context = {
        'news': news.to_dict()
    }

    return render_template('admin/news_review_detail.html', context=context)


@admin_blue.route('/news_review_action', methods=['POST'])
def news_review_action():
    """实现新闻审核后端逻辑：就是修改新闻的状态
    1.接受参数：news_id, action
    2.校验参数：判断参数是否齐全，判断action是否在范围内
    3.判断要审核的新闻是否存在
    4.根据action修改新闻的状态(核心代码)
    5.同步到数据库
    6.响应结果
    """

    # 1 接受参数　
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 2 校验参数
    if not all([news_id, action]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')
    if action not in ['accept', 'reject']:
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')

    # 判断需要审核的新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询新闻失败')
    if not news:
        return jsonify(errno=response_code.RET.NODATA, errmsg='新闻不存在')

    # 根据　action的值修改新闻的状态
    if action == 'accept':
        news.status = 0
    else:
        # 拒绝通过　必须携带参数，拒绝理由
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少拒绝理由')

        news.status = -1
        news.reason = reason

    # 同步到数据库
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=response_code.RET.DBERR, errmsg='保存到数据库失败')

    # 返回响应结果
    return jsonify(errno=response_code.RET.OK, errmsg='OK')

@admin_blue.route('/news_edit')
def news_edit():
    """
    新闻板式编辑列表
    :return:
    """
    # 获取分页
    page = request.args.get('p', 1)

    # 校验参数
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1

    # 分页查询
    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = News.query.filter(News.status == 0).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        logging.error(e)
        abort(404)


    # 构造渲染数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    context = {
        'news_list': news_dict_list,
        'total_page': total_page,
        'current_page': current_page
    }


    # 返回响应结果
    return render_template('admin/news_edit.html', context=context)


@admin_blue.route('/news_edit_detail/<int:news_id>', methods=['GET', 'POST'])
def news_edit_detail(news_id):
    """新闻板式编辑详情
    1.查询新闻详情数据
    2.查询新闻分类数据（"最新"分类除外）
    3.构造渲染数据
    4.渲染界面
    """

    if request.method == 'GET':
        # 1 查询新闻详情数据
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            logging.error(e)
            abort(404)

        if not news:
            abort(404)

        # 2 查询新闻分类数据（‘最新’分类除外）
        categories = []
        try:
            categories = Category.query.all()
            categories.pop(0)   # 遍历出所有的新闻分类，并把第一个分类‘最新’分类删除
        except Exception as e:
            logging.error(e)
            abort(404)

        # 构造渲染数据
        context = {
            'news': news.to_dict(),
            'categories': categories
        }

        # 渲染界面
        return render_template('admin/news_edit_detail.html', context=context)

    # 2.实现新闻板式编辑后端
    if request.method == 'POST':
        # 2.1 接受参数
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")

        # 2.2 校验参数
        if not all([title, digest, content, category_id]):
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')

        try:
            news = News.query.get(news_id)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='查询新闻数据失败')

        if not news:
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='新闻不存在')

        # 2.3 如果运营修改了图片，我们就需要将图片上传到七牛云；反之，就不管
        if index_image:
            try:
                index_image_data = index_image.read()
            except Exception as e:
                logging.error(e)
                return jsonify(errno=response_code.RET.PARAMERR, errmsg='图片参数错误')

            try:
                key = upload_file(index_image_data)
            except Exception as e:
                logging.error(e)
                return jsonify(errno=response_code.RET.THIRDERR, errmsg='上传图片到七牛云失败')

            # 需要将key修改
            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

        # 2.4 将新闻编辑的数据保存到模型对象，并同步到数据库
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            logging.error(e)
            return jsonify(errno=response_code.RET.DBERR, errmsg='保存数据失败')

        # 2.5 响应结果
        return jsonify(errno=response_code.RET.OK, errmsg='OK')


@admin_blue.route('/news_type', methods=['GET', 'POST'])
def news_type():
    """新闻分类"""
    if request.method == 'GET':
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            logging.error(e)
            abort(404)

        # 删除最新分类
        categories.pop(0)

        # 构造渲染数据
        context = {
            'categories': categories
        }

        return render_template('admin/news_type.html', context=context)

    # 2.增加或者修改新闻分类
    if request.method == 'POST':
        # 2.1 接受参数：cid, cname
        cid = request.json.get('id')
        cname = request.json.get('name')

        if not cname:
            return jsonify(errno=response_code.RET.PARAMERR, errmsg='缺少参数')

        # 修改分类
        if cid:
            try:
                category = Category.query.get(cid)
            except Exception as e:
                logging.error(e)
                return jsonify(errno=response_code.RET.DBERR, errmsg='查询数据库失败')
            if not category:
                return jsonify(errno=response_code.RET.NODATA, errmsg='分类不存在')

            category.name = cname

        # 增加分类
        else:
            category = Category()
            category.name = cname
            db.session.add(category)

        # 同步到数据库
        try:
            db.session.commit()
        except Exception as e:
            logging.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DATAERR, errmsg='更新数据失败')


        # 返回响应结果
        return jsonify(errno=response_code.RET.OK, errmsg='更新数据成功')





